package com.mouliu.base.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 缓存器
 *
 * @author mouliu
 * @create 2018-05-13-上午8:55
 */
public class CacheDemo {
    //缓存器
    private Map<String,Object> map =
            new HashMap<>();
    private ReadWriteLock rwl = new ReentrantReadWriteLock();

    public static void main(String[] args){

    }
    public Object get(String id) {
        Object value = null;
        rwl.readLock().lock();//首先开启读锁，从缓存中去取
        try {
            value = map.get(id);
            if (value == null) {//如果缓存中没有释放读锁，上写锁
                rwl.readLock().unlock();
                rwl.writeLock().lock();
                try {
                    if (value == null) {
                        value = "aaa";//此时可以去数据库中查找，这里简单的模拟一下
                    }
                } finally {
                    rwl.writeLock().unlock();//释放写锁
                }
                rwl.writeLock().unlock();//然后再上读锁
            }
        } finally {
            rwl.readLock().unlock();
        }
        return value;
    }
}
